from config.config import config
from config.const import Const
from flask import Flask


def create_app(config_name=Const.ENV):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    # register extensions
    register_extensions(app)

    # register blueprints
    register_blueprints(app)

    # register sql debug
    register_sql_debug(app)

    # register global handler
    register_global_errors(app)

    return app


def register_extensions(app):
    """注册插件"""

    from extensions import db, sentry

    db.init_app(app)
    sentry.init_app(app)


def register_blueprints(app):
    """注册蓝图"""

    from .main.urls import main_blueprint

    app.register_blueprint(main_blueprint)

    from .api.urls import api_blueprint

    app.register_blueprint(api_blueprint, url_prefix="/api")


def register_global_errors(app):
    """在这里注册全局异常处理, 比如处理无权限之类的"""

    pass


def register_sql_debug(app):
    """注册sqldebug"""

    if Const.ENV == 'debug':
        from utils.debug import sql_debug

        app.after_request(sql_debug)
